import React, { useState,useEffect } from 'react';
import { observer } from 'mobx-react';
import { Link } from 'react-router-dom';
import Skeleton from 'react-loading-skeleton'
import 'react-loading-skeleton/dist/skeleton.css'
import BookStore from '../stores/BookDataStore';
import { Bdiv,Bh1,Bbtu,Bul,Bli,Blink} from "../styles/HomeCss";

const BlogHearder = () => {
    return (
        <Bdiv>
            <Bh1>书籍列表</Bh1>
            <Link to="/">
                <Bbtu>主页</Bbtu>
            </Link>
        </Bdiv>
    )
}

class ErrorBoundary extends React.Component {
    state = { 
        hasError: false,
        error: null,
    };
    
    static getDerivedStateFromError(error) {
        return { 
            hasError: true,
            error: error,
        };  
    }
    componentDidCatch(error, errorInfo) {
        console.error("Error caught by ErrorBoundary:", error, errorInfo);
    }
    handleRetry = () => {
        this.setState({ hasError: false });
        BookStore.fetchBooks();
    };
    
    render() {
        if (this.state.hasError) {
            return (
                <Bdiv>
                    <BlogHearder/>
                    <Bul>
                        <p>{this.state.error?.message}</p>
                        <Bbtu onClick={this.handleRetry}>
                            重试
                        </Bbtu>
                    </Bul>
                </Bdiv>
            );
        }
        return this.props.children;
    }
}

const Blog = observer(() => {

    const [fetchError, setFetchError] = useState(null);

    useEffect(() => {
        const loadBooks = async () => {
            try {
                await BookStore.fetchBooks();
                setFetchError(null);
            } catch (error) {
                setFetchError(error);
            }
        };
        loadBooks();
    }, []);
    if (fetchError) {
        throw fetchError;
    }

    if(BookStore.isLoading){
        return(
        <Bdiv className = 'lbooklist'>
            <BlogHearder/>
            <Bul>
                {BookStore.books.map(books =>(
                <Bli key={books.id}>
                    <Skeleton 
                        enableAnimation={BookStore.books.length < 50}
                        duration={BookStore.books.length >= 30 ? 0 : 1}
                        baseColor="rgba(128, 128, 128, 0.2)"
                        highlightColor="rgba(128, 128, 128, 0.4)"
                    />
                </Bli>
                ))}
            </Bul>
        </Bdiv>
        )
    }

    return(
    <Bdiv className = 'nbooklist'>
        <BlogHearder/>
        <Bul>
            {BookStore.books.map(books =>(
            <Bli key={books.id}>    
                <Blink to={`/AboutBook/${books.id}`}>
                    {books.name}
                </Blink>
            </Bli>
            ))}
        </Bul>
    </Bdiv>);
});

export { ErrorBoundary as BErrBoundary};
export default Blog;
